package algorithm;

/**
 * 字符串相乘
 */
public class Leetcode_multiply_43 {
    public static String multiply(String num1, String num2) {
        int len1 = num1.length() - 1, len2 = num2.length() - 1;
        if (len1 == 0 || len2 == 0) {
            return "0";
        }
        String ans = "0";
        for(int i = len2 ; i >= 0; i--) {
            StringBuilder sb = new StringBuilder();
            int add = 0;
            for (int j = len1 - i; j > i; i--) {
                sb.append(0);
            }
            int y = num2.charAt(i) - '0';
            for (int j = len1; j >= 0; j--) {
                int x = num1.charAt(j) - '0';
                int result = x * y + add;
                add = result / 10;
                sb.append(result % 10);
            }
            if (add != 0) {
                sb.append(add % 10);
            }
            ans = addStr(ans, sb.reverse().toString());
        }
        return ans;
    }
    public static String addStr(String ans, String sb) {
        int array = 0, i = ans.length() - 1, j = sb.length();
        StringBuilder stringBuilder = new StringBuilder();
        while(i >= 0 || j >= 0 || array > 0) {
            int x = i >= 0 ?  ans.charAt(i) - '0' : 0;
            int y = j >= 0 ? sb.charAt(j) - '0' : 0;
            int result = x + y + array;
            array = result / 10;
            stringBuilder.append(result % 10);
        }
        stringBuilder.reverse();
        return stringBuilder.toString();
    }

}
